# -*- coding: utf-8 -*-
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from Util.Return import *
from Util.SQL import *
from Util.Process import *
from Data.DataAPI.Landsat.API import LandsatAPI
from Data.DataAPI.Sentinel.API import SentinelAPI
import concurrent.futures

API = {
    "Landsat": LandsatAPI(),
    "Sentinel": SentinelAPI()
}


def get_info(dataset, address, date):  # 从API获得数据信息，支持bbox和point两种查询方式
    bbox = get_spatial(address, True)
    if bbox != -1:
        scenes = API[dataset].request(date=date, bbox=bbox)
    else:
        point = get_spatial(address, False)
        scenes = API[dataset].request(date=date, point=point)
    insert(scenes, 'data')
    return scenes


def get_data(dataset, scenes):  # 从API获得原始数据
    API[dataset].download(scenes)  # 下载数据
    API[dataset].preprocess(scenes)  # 处理数据
    API[dataset].upload(scenes)  # 上传数据


def get_all(dataset, address, date):  # 获得信息并进行下载
    scenes = get_info(dataset, address, date)
    scene_list = [scene['scene_id'] for scene in scenes]
    with concurrent.futures.ThreadPoolExecutor(max_workers=get_config("config", "max_workers")) as executor:  # 线程池
        for scene_id in scene_list:
            available_tag = select(
                "SELECT count(1) as num FROM data WHERE scene_id = '{scene_id}' and available = 1".format(
                    scene_id=scene_id))[0]['num']
            if available_tag == 0:  # 若不存在或不可用，则不去下载
                executor.submit(get_data, dataset, [scene_id])
            else:
                INFO("WARNING", f"DataAchieve : {scene_id} already exists, skipping subsequent steps")